#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;

void Usage(string proc)
{
    cout << "Usage:\n\t" << proc << " client_ip client_port\n"
         << endl;
}
// ./tcpclient serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        cerr << "sockfd error\n"
             << endl;
        exit(1);
    }
    struct sockaddr_in server;
    // 构建目标主体的socket信息
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    int n = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
    if (n < 0)
    {
        cerr << "connect error\n";
        exit(3);
    }
    //::close(sockfd);
    while (true)
    {
        std::cout << "Please Enter# ";
        std::string outstring;
        std::getline(std::cin, outstring);

        //发消息
        ssize_t s = send(sockfd, outstring.c_str(), outstring.size(), 0); // write
        if (s > 0)
        {
            char inbuffer[1024];
            //收消息
            ssize_t m = recv(sockfd, inbuffer, sizeof(inbuffer) - 1, 0);
            if (m > 0)
            {
                inbuffer[m] = 0;
                std::cout << inbuffer << std::endl;
            }
            else
            {
                break;
            }
        }
        else
        {
            break;
        }
    }
    return 0;
}